<?php
namespace Admin\Model;

use Think\Model;

class StudentModel extends Model {



    public function getStudentByWhere($where,$limit='') {
        is_null($where) && $where='';
        return $this->where($where)->order('student_id asc')->limit($limit)->select();
    }

    public function getCountByWhere($where) {
        is_null($where) && $where='';
        return $this->where($where)->count();
    }


    public function getStudentByCid($cid) {
        $map['class_id'] = $cid;
        return $this->where($map)->order('student_id asc')->select();
    }

    public function getStudentNameById($id) {
        return $this->where('id = '.$id)->getField('name');
    }


    /**
     * 根据班级id,获取该班级所有学生的id
     *
     * @param $cid
     * @param string $type 返回类型
     * @return array|string
     */
    public function getSidsByCid($cid,$type='array') {
        $map['class_id'] = $cid;
        $sql = "SELECT id FROM __STUDENT__ WHERE class_id = ".$cid." ORDER BY student_id ASC";
        $res = $this->query($sql);
        $res = $this->handlerArray($res);
        if ($type === 'array') {
            empty($res) && $res=array();
            return $res;
        } else if ($type === 'string') {
            empty($res) && $res='';
            return explode(',',$res);
        }
    }


    /**
     * 根据学生ID数组,获取所有学生
     *
     * @param $idArr
     * @return array
     */
    public function getStudentArrByIdArr($idArr) {
        $studentArr = array();
        foreach ($idArr as $v) {
            $s = $this->find($v);
            if (!empty($s)) $studentArr[] = $s;
        }

        return $studentArr;
    }


    /**
     * 获取班级总人数
     *
     * @param $cid
     * @return mixed
     */
    public function getCountByCid($cid) {
        return $this->where('class_id = '.$cid)->count();
    }


    public function _get($id) {
        if (empty($id)) return array();
        return $this->find($id);
    }

    public function _find($id) {
        return $this->find($id);
    }

    public function _add($data) {

        $map['student_id'] = $data['student_id'];
        $s = $this->where($map)->find();
        if (!empty($s)) return '101301';

        $flag = $this->add($data);
        if ($flag !== false) return '000000';
        return '111111';
    }

    public function _save($data) {
        $map['student_id'] = $data['student_id'];
        $map['id'] = array('neq',$data['id']);
        $s = $this->where($map)->find();
        if (!empty($s)) return '101301';

        $flag = $this->save($data);
        if ($flag !== false) return '000000';
        return '111111';
    }


    public function _del($id) {
        $flag = $this->delete($id);
        if ($flag !== flase) return '000000';
        return '111111';
    }


    protected function handlerArray($data) {
        $arr = array();
        foreach ($data as $v) {
            $arr[] = $v['id'];
        }

        return $arr;
    }

}